package leetcode.code1818;

import java.util.TreeSet;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int mod = (int) 1e9 + 7;

	public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {
		int n = nums1.length;
		long ans = 0;
		TreeSet<Integer> set = new TreeSet<>();
		for (int num : nums1) {
			set.add(num);
		}
		int max = Integer.MIN_VALUE;
		for (int i = 0; i < n; i++) {
			int num2 = nums2[i];
			Integer n2 = set.ceiling(num2);
			int curAns = Math.abs(nums1[i] - num2);
			Integer n1 = set.floor(num2);
			if (n1 != null) {
				max = Math.max(max, curAns - Math.abs(n1 - num2));
			}
			if(n2!=null) {
				max = Math.max(max, curAns - Math.abs(n2 - num2));
			}
			ans += curAns;
			ans %= mod;
		}
		return (int) (ans - max + mod) % mod;
	}

	@Override
	public void debug4() {
		H.compare(3, this.minAbsoluteSumDiff(H.str2array3("[1,7,5]"), H.str2array3("[2,3,5]")));
		H.compare(0, this.minAbsoluteSumDiff(H.str2array3("[2,4,6,8,10]"), H.str2array3("[2,4,6,8,10]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
